<?php

namespace common\behavior\CommonMessagePushing;

use common\model\ProjectMemberModel;
use common\model\TaskModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\OptionsService;
use common\service\TaskAssembleService;
use common\service\TaskService;
use common\service\UserService;
use Webman\Stomp\Client;

/**
 * 任务返修行为 消息通知
 */
class TaskRepairBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'from_demand_order' => 'boolval',
                'changed_id_list' => 'array_map,intval',
                'need_repair_task_id' => 'intval',
                'relation_note_text' => 'strval|trim',
            ],
            [
                'from_demand_order' => false,
                'changed_id_list' => [],
                'need_repair_task_id' => 0,
                'relation_note_text' => '',
            ],
            'data',
            ['type' => 'task_repair_notice'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($fromDemandOrder, $changedIdList, $needRepairTaskId, $relationNoteText) = $params;
        if (empty($changedIdList) || empty($needRepairTaskId)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $queryFields = [
            'task.id',
            'task.name',
            'task.executor',
            'task.tenant_id',
            'task.project_id',
            'task.assignee_producer',
            'task.department_id',
            'task.entity_module_id',

            'entity.id',
            'entity.name',
            'entity.initial_episode_code',
            'entity.showings_number',
        ];
        $relatePeopleTasks = model(TaskModel::class)
            ->join('entity on entity.id = task.entity_id')
            ->where(['task.id' => ['IN', $changedIdList]])
            ->field(build_complex_query_fields($queryFields, '__'))
            ->select();


        $relatedTasks = model(TaskModel::class)
            ->where(['task.id' => ['IN', $changedIdList]])
            ->select();

        // 记录异常通知
        foreach ($relatedTasks as $task) {
            $queueData = [
                'module_code' => 'task',
                'type' => 'repair',
                'info' => $relationNoteText,
                'data' => $task,
            ];
            Client::send("abnormal_info_store", build_queue_data_with_xu($queueData));
        }

        // 抽取数据
        $userIdList = [];
        $projectIdList = [];
        $departmentIdList = [];
        $tenantIdList = [];
        $needRepairTaskName = '';
        $needRepairTaskData = null;
        foreach ($relatePeopleTasks as &$relatePeopleTask) {
            $relatePeopleTask = separate_complex_query_data($relatePeopleTask, '__');
            $userIdList[$relatePeopleTask['task']['executor']] = $relatePeopleTask['task']['executor'];
            $userIdList[$relatePeopleTask['task']['assignee_producer']] = $relatePeopleTask['task']['assignee_producer'];
            $projectIdList[$relatePeopleTask['task']['project_id']] = $relatePeopleTask['task']['project_id'];
            $departmentIdList[$relatePeopleTask['task']['department_id']] = $relatePeopleTask['task']['department_id'];
            $tenantIdList[$relatePeopleTask['task']['tenant_id']] = $relatePeopleTask['task']['tenant_id'];
            if ($relatePeopleTask['task']['id'] == $needRepairTaskId) {
                $needRepairTaskName = TaskAssembleService::getInstance()->getNotifyTaskName($relatePeopleTask['entity'], $relatePeopleTask['task']);
                $needRepairTaskData = $relatePeopleTask;
            }
        }
        unset($departmentIdList[0], $tenantIdList[0], $projectIdList[0]);

        // 需求单发起的返修，对于单个返修通知 屏蔽管理层
        // 项目生产制片查询 组装项目生产制片map
        $projectMemberList = [];
        if (!$fromDemandOrder) {
            $projectMemberList = model(ProjectMemberModel::class)
                ->where([
                    'project_id' => ['IN', implode(',', $projectIdList)],
                    'role_code' => TaskService::EXECUTIVE_PRODUCER_CODE,
                ])
                ->field('project_id,user_id')
                ->group('project_id,user_id')
                ->select();
            $userIdList = array_merge($userIdList, array_column($projectMemberList, 'user_id', 'user_id'));
        }
        $projectMemberMap = [];
        foreach ($projectMemberList as $projectMember) {
            $projectMemberMap[$projectMember['project_id']][] = $projectMember['user_id'];
        }
        unset($userIdList[0]);
        // 根据上面的已有user_id 查询当前系统userMap
        $userList = [];
        if (!empty($userIdList)) {
            $userList = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIdList)]])->select();
            $userList = array_column($userList, null, 'id');
        }

        // 根据部门id查询组长 组装部门组长map
        // 需求单发起的返修，对于单个返修通知 屏蔽管理层
        $userDepartmentMap = [];
        if (!$fromDemandOrder) {
            if (!empty($departmentIdList)) {
                $filter = [
                    'tenant_id' => ['-in', implode(',', $tenantIdList)],
                    'department_id' => ['-in', implode(',', $departmentIdList)],
                    'role_code' => TaskService::HEADMAN_CODE,
                ];
                $userDepartmentMap = UserService::getInstance()->getDepartmentSaasUserMap($filter);
            }
        }

        unset($relatePeopleTask);

        $templateId = OptionsService::getInstance()->getTaskRemindCommonTemplateId();


        // 遍历每个任务 组长要通知的人员
        $messageGenerated = [];
        foreach ($relatePeopleTasks as $relatePeopleTask) {
            $currentNotifyUserList = [];

            if ($relatePeopleTask['task']['executor'] > 0 && isset($userList[$relatePeopleTask['task']['executor']])) {
                $currentNotifyUserList[$relatePeopleTask['task']['executor']] = $userList[$relatePeopleTask['task']['executor']];
            }

            if ($relatePeopleTask['task']['assignee_producer'] > 0 && isset($userList[$relatePeopleTask['task']['assignee_producer']])) {
                $currentNotifyUserList[$relatePeopleTask['task']['assignee_producer']] = $userList[$relatePeopleTask['task']['assignee_producer']];
            }

            if ($relatePeopleTask['task']['department_id'] > 0 && isset($userDepartmentMap[$relatePeopleTask['task']['department_id']])) {
                foreach ($userDepartmentMap[$relatePeopleTask['task']['department_id']] as $departmentSaasUser) {
                    $currentNotifyUserList[$departmentSaasUser['id']] = $departmentSaasUser;
                }
            }

            if ($relatePeopleTask['task']['project_id'] > 0 && isset($projectMemberMap[$relatePeopleTask['task']['project_id']])) {
                foreach ($projectMemberMap[$relatePeopleTask['task']['project_id']] as $projectMemberUserId) {
                    if (isset($userList[$projectMemberUserId])) {
                        $currentNotifyUserList[$projectMemberUserId] = $userList[$projectMemberUserId];
                    }
                }
            }

            if (empty($currentNotifyUserList)) {
                continue;
            }

            $taskName = TaskAssembleService::getInstance()->getNotifyTaskName($relatePeopleTask['entity'], $relatePeopleTask['task']);
            // 通知文本组装
            if ($needRepairTaskId == $relatePeopleTask['task']['id']) {
                $noteText = '任务' . $taskName . '被返修了';
            } else {
                if ($relatePeopleTask['entity']['id'] != $needRepairTaskData['entity']['id']) {
                    $relateType = '关联';
                } else {
                    $relateType = '上游';
                }
                $noteText = '任务' . $taskName . '的' . $relateType . $needRepairTaskName . '返修了';
            }

            $notifyParam = [
                'first' => '任务返修通知',
                'note_text' => $noteText,
                'remark' => "请及时查看",
                'tenant_id' => $relatePeopleTask['task']['tenant_id'],
                'project_id' => $relatePeopleTask['task']['project_id'],
                'task_id' => $relatePeopleTask['task']['id'],
                'module_code' => in_array(module_by_id($relatePeopleTask['task']['entity_module_id'])['code'], ['design', 'level', 'asset']) ? 'asset' : 'shot',
                'message_key' => 'task_repaired',
            ];

            foreach ($currentNotifyUserList as $currentNotifyUser) {
                // 异步发送通知
                $messageGenerated[] = [
                    "param" => $notifyParam,
                    'receiver' => $currentNotifyUser['union_id'],
                    'template_id' => $templateId,
                    'content_type' => 'card_message',
                    'notice_type' => 'message_task',
                    'is_popup' => 1,
                    'message_key' => $notifyParam['message_key'],
                ];
            }
        }


        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
